﻿namespace Grep.SharePoint.Lib.Extensions
{
    using System.Collections.Generic;
    using Microsoft.SharePoint.WebControls;

    public static class ToolBarMenuButtonExtensions
    {
        public static SubMenuTemplate AddSubMenu(this ToolBarMenuButton self, string id, string displayName,
                                                 string imageUrl, string description)
        {
            if (self.MenuTemplateControl == null)
            {
                return null;
            }

            SubMenuTemplate child = SubMenuTemplateExtensions.CreateSubMenu(id, displayName, imageUrl, description);
            self.MenuTemplateControl.Controls.Add(child);
            return child;
        }

        public static SubMenuTemplate AddSubMenuAt(this ToolBarMenuButton self, int index, string id, string displayName,
                                                   string imageUrl, string description)
        {
            if (self.MenuTemplateControl == null)
            {
                return null;
            }

            SubMenuTemplate child = SubMenuTemplateExtensions.CreateSubMenu(id, displayName, imageUrl, description);
            self.MenuTemplateControl.Controls.AddAt(index, child);
            return child;
        }

        public static IEnumerable<MenuItemTemplate> EnumMenuItems(this ToolBarMenuButton self)
        {
            if (self.MenuTemplateControl != null)
            {
                foreach (object item in self.MenuTemplateControl.Controls)
                {
                    if (item is MenuItemTemplate)
                    {
                        yield return item as MenuItemTemplate;
                    }
                }
            }
        }

        public static IEnumerable<SubMenuTemplate> EnumSubMenus(this ToolBarMenuButton self)
        {
            if (self.MenuTemplateControl != null)
            {
                foreach (object item in self.MenuTemplateControl.Controls)
                {
                    if (item is SubMenuTemplate)
                    {
                        yield return item as SubMenuTemplate;
                    }
                }
            }
        }
    }
}